package DHBW.App;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import android.widget.EditText;
import android.util.Log;
import android.view.*;
import DHBW.BT.*;
import DHBW.Convert.CharConverter;

public class DHBW_BT_TestActivity extends Activity {
	
	public static final boolean D = true;
	public static final String TAG = "DHBW_BT";
	
    // Name of the connected device
    private String mConnectedDeviceName = null;
	
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
  
    // Layout Views
    private TextView mTitle;
    
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothDHBW mBluetoothDHBW = null;
    
    private int menuitem = 0;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);
        mTitle.setText(R.string.title_not_connected);
        
        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.dhbw_values, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(new MyOnItemSelectedListener());
        
        final Button button1 = (Button) findViewById(R.id.button1);
        final EditText edit1 = (EditText) findViewById(R.id.editText1); 
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	int value = 0;
            	switch (menuitem) {
            	case 0:
            		value = mBluetoothDHBW.getRPM();
            		break;
            	case 1:
            		value = mBluetoothDHBW.getCurrent();
            		break;
            	case 2:
            		value = mBluetoothDHBW.getVoltage();
            		break;
            	case 3:
            		value = mBluetoothDHBW.getTemperature();
            		break;
            	case 4:
           			mBluetoothDHBW.setContinuous(!mBluetoothDHBW.getContinuous());
            		break;
            	}	
            	edit1.setText(CharConverter.threeDigit2Char(value), 0, 3);
            }
        });
        
        
        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        mBluetoothDHBW = new BluetoothDHBW(this,mHandler);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
//            if (mChatService == null) setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
//        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
//            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
//              mChatService.start();
//            }
//        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        }
        return false;
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
          menuitem = pos;
          Log.d("BT...", "spinner-pos:" + menuitem);
        }

        public void onNothingSelected(AdapterView parent) {
          // Do nothing.
        }
    }
    
    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mBluetoothDHBW.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
//                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
    /**
     * The Handler that gets information back from the BluetoothChatService
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Log.d("Handler","New Message");
            switch (msg.what) {
            case BluetoothDHBW.MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothDHBW.STATE_CONNECTED:

                	break;
                case BluetoothDHBW.STATE_CONNECTING:
                    
                	break;
                case BluetoothDHBW.STATE_NONE:
                    
                	break;
                }
                break;
            case BluetoothDHBW.MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                break;
            case BluetoothDHBW.MESSAGE_NOTICE:
//                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
//                               Toast.LENGTH_SHORT).show();
                break;
            case BluetoothDHBW.MESSAGE_NEW:
            	PedelecFrame tmpData = (PedelecFrame) msg.obj;
            	int cycle1 = 1; 
            	int cycle2 = 10;

             	if (tmpData.id() % cycle1 == 0) {
            		final EditText edit1 = (EditText) findViewById(R.id.editText1);
            		String tmpOutValues = "";
            		tmpOutValues = tmpData.id()+":"+tmpData.rpm()+"-"+tmpData.current()+"-"+tmpData.voltage()+"-"+tmpData.temperature();
            		edit1.setText(tmpOutValues.toCharArray(), 0, tmpOutValues.length());
            	}
            	
            	if (tmpData.id() % cycle2 == 0) {
            		//abc = tmpData.current();
            	}
            	break;
            }
        }
    };
    
    
}